package com.hfjyz.system.category.dao;

import java.util.List;

import com.hfjyz.base.bean.SearchCondition;
import com.hfjyz.base.dao.BaseDao;
import com.hfjyz.base.dao.PagingHibernateCallback;
import com.hfjyz.base.entity.CategoryEntity;

public class CategoryDao extends BaseDao<CategoryEntity> {

    public CategoryDao() {
        super(CategoryEntity.class);
    }

    public CategoryDao(Class<?> clazz) {
        super(clazz);
    }

    @SuppressWarnings("unchecked")
    public List<CategoryEntity> findCategory(SearchCondition cond) {
        String hql = "from CategoryEntity cate where cate.categoryParent is null " + cond.getOrderString();
        PagingHibernateCallback callback = new PagingHibernateCallback(hql, cond.getPageNum(),
                cond.getRowCountPerPage());
        List<CategoryEntity> result = hibernateTemplate.executeFind(callback);
        return result;
    }
    
    @SuppressWarnings("unchecked")
    public List<CategoryEntity> findCategory(SearchCondition cond, Integer parentId) {
        String hql = "from CategoryEntity cate where cate.categoryParent=? " + cond.getOrderString();
        PagingHibernateCallback callback = new PagingHibernateCallback(hql, cond.getPageNum(),
                cond.getRowCountPerPage(), parentId);
        List<CategoryEntity> result = hibernateTemplate.executeFind(callback);
        return result;
    }
    
    @SuppressWarnings("unchecked")
    public List<CategoryEntity> findCategory(Integer parentId) {
        List<CategoryEntity> result = null;
        if (parentId == null) {
            String hql = "from CategoryEntity cate where cate.categoryParent is null order by cate.id";
            result = hibernateTemplate.find(hql);
        } else {
            String hql = "from CategoryEntity cate where cate.categoryParent=? order by cate.id";
            result = hibernateTemplate.find(hql, parentId);
        }
        return result;
    }

    @SuppressWarnings("unchecked")
    public long countCategory(SearchCondition cond) {
        String hql = "select count(category.id) from CategoryEntity as category where category.categoryParent is null";
        List<Object> result = hibernateTemplate.find(hql);

        return (Long) result.get(0);
    }
    
    @SuppressWarnings("unchecked")
    public long countCategory(SearchCondition cond, Integer parentId) {
        String hql = "select count(category.id) from CategoryEntity as category where category.categoryParent=?";
        List<Object> result = hibernateTemplate.find(hql, parentId);

        return (Long) result.get(0);
    }

    @SuppressWarnings("unchecked")
    public long countCategoryByName(String name) {
        String hql = "select count(category.id) from CategoryEntity as category where category.categoryName=?";
        List<Object> result = hibernateTemplate.find(hql, name);
        return (Long) result.get(0);
    }
}
